using System.ComponentModel;

namespace Rsdn.Janus
{
    using System;
    using JetBrains.Annotations;
    using SmartApp;

    [Service(typeof (IBrowserService))]
    internal class JBrowserService : IBrowserService
    {
        private readonly IServiceProvider _serviceProvider;
        private WebBrowserForm _webBrowserForm;

        private string urlInternal;

        public JBrowserService([NotNull] IServiceProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            _serviceProvider = provider;
        }

        #region IBrowserService Members

        private void OpenUrlInternal()
        {
            if (_webBrowserForm == null || _webBrowserForm.IsDisposed)
            {
                _webBrowserForm = new WebBrowserForm(_serviceProvider);
            }

            _webBrowserForm.EnsureVisible();
            _webBrowserForm.NavigateTo(urlInternal);
        }

        public void OpenUrl([NotNull] string url)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            IUIShell uiShell = _serviceProvider.GetRequiredService<IUIShell>();
            AsyncOperation asyncOperation = uiShell.CreateUIAsyncOperation();

            urlInternal = url;
            asyncOperation.Post(OpenUrlInternal);
        }

        #endregion
    }
}